<?php

class SiteController extends Controller
{
	public $layout='column1';

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}	
	
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}
	
	/**
	 * Displays the fileupload page
	 */
	public function actionFileupload()
	{
		Yii::app()->session['username'] = Yii::app()->user->name;
		$this->render('upload');
	}
	
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()) {
				if (Yii::app()->user->checkAccess('Promo')) { $this->redirect(array('/promo/admin')); }
				else if (Yii::app()->user->checkAccess('Editor')) {	$this->redirect(array('/editors/admin')); }								
				else if (Yii::app()->user->checkAccess('Markup')) {	$this->redirect(array('/markups/admin')); }									
			}
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionQuick() {
        $model=new QuickForm;
            $model->attributes=$_POST['QuickForm'];
            if($model->validate()) {
                $headers="From: denis@elcp.ru\r\nReply-To: denis@elcp.ru";
                $body = "\n\nSender: ".iconv("windows-1251", "UTF-8", $model->name)."\t Desription: ".iconv("windows-1251", "UTF-8", $model->desription);
                mail(Yii::app()->params['adminEmail'],'Feedback!',$body,$headers);
            }
        $this->redirect(array('post/index'));
	}
	
	public function actionIcal() {
        $model=new IcalForm;
            $model->attributes=$_POST['IcalForm'];
            if($model->validate()) {
				$from_name = $model->from_name;
				$from_address = "denis@elcp.ru";
				$subject = $model->subject;
				$emails[] = $model->emails;
				$meeting_description = $model->meeting_description;
				$meeting_location = $model->meeting_location;
				$meeting_name = "Invite";
				$meeting_duration = 3600;			 
			 
				//Convert MYSQL datetime and construct iCal start, end and issue dates
				$meetingstamp = STRTOTIME($model->meeting_date . " UTC");    
				$dtstart= GMDATE("Ymd\THis\Z",$meetingstamp);
				$dtend= GMDATE("Ymd\THis\Z",$meetingstamp+$meeting_duration);
				$todaystamp = GMDATE("Ymd\THis\Z");
			 
				//Create unique identifier
				$cal_uid = DATE('Ymd').'T'.DATE('His')."-".RAND()."@mydomain.com";
			 
				//Create Mime Boundry
				$mime_boundary = "----Meeting Booking----".MD5(TIME());
			 
				//Create Email Headers
				$headers = "From: ".$from_name." <".$from_address.">\n";
				$headers .= "Reply-To: ".$from_name." <".$from_address.">\n";
			 
				$headers .= "MIME-Version: 1.0\n";
				$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
				$headers .= "Content-class: urn:content-classes:calendarmessage\n";
			 
				//Create Email Body (HTML)
				$message .= "--$mime_boundary\n";
				$message .= "Content-Type: text/html; charset=UTF-8\n";
				$message .= "Content-Transfer-Encoding: 8bit\n\n";
			 
				$message .= "<html>\n";
				$message .= "<body>\n";
				$message .= '<p>'.$model->mtext.'</p>';   
				$message .= "</body>\n";
				$message .= "</html>\n";
				$message .= "--$mime_boundary\n";
			 
				//Create ICAL Content (Google rfc 2445 for details and examples of usage) 
$ical = 'BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:'.$from_address.'
DTSTART:'.$dtstart.'
DTEND:'.$dtend.'
LOCATION:'.$meeting_location.'
TRANSP:OPAQUE
SEQUENCE:0
UID:'.$cal_uid.'
DTSTAMP:'.$todaystamp.'
DESCRIPTION:'.$meeting_description.'
SUMMARY:'.$subject.'
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR';   
			 
				$message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST\n';
				$message .= "Content-Transfer-Encoding: 8bit\n\n";
				$message .= $ical;            

				foreach ($emails as $email) {
					@MAIL($email, $subject, $message, $headers);
				}				

            }
        $this->redirect(array('post/index'));
	}
	
	/**
	 * Restores the database for the demo application.
	 */
	public function actionRestore()
	{
		$db = Yii::app()->getDb();
		$schema=file_get_contents(Yii::app()->basePath.'/data/reset.sql');
		$schema=preg_split("/;\s+/", trim($schema, ';'));
		foreach( $schema as $sql )
			$db->createCommand($sql)->execute();
		Yii::app()->user->setFlash('success', 'Database has been restored!');
		$this->redirect(Yii::app()->homeUrl);
	}
}